<template>
  <div>
    <el-upload
        class="upload-content"
        :action="$http.adornUrl('/admin/file/upload/element')"
        :before-upload="beforeAvatarUpload"
        :disabled="disabled"
        :file-list="imageList"
        :headers="{Authorization: $cookie.get('Authorization')}"
        :on-preview="handlePictureCardPreview"
        :on-progress="handleProgress"
        :on-remove="handleRemove"
        :on-success="handleUploadSuccess"
        :on-error="handleError"
        accept=".jpg,.jpeg,.png,.bmp,.webp,.svg,.txt, .pdf,.doc,.docx,.ppt,.pptx,.pps,.ppsx,.odt,.xls,.xlsx,.wps,.rar,.zip,.7z"
        list-type="picture-card">
      <i class="el-icon-plus"></i>
      <template #file="{ file }">
        <div
            @click.stop="imageSave(file)">
                    <span v-if="!isImg(file)" class="el-upload-list_file">
                            <span v-if="isWord(file)">WORD</span>
                            <span v-else-if="isPdf(file)">PDF</span>
                            <span v-else-if="isExcel(file)">EXCEL</span>
                            <span v-else-if="isTXT(file)">TXT</span>
                            <span v-else-if="isZip(file)">ZIP</span>
                            <i class="el-icon-collection wordImg" style="font-size: 46px;" v-else></i>
                        </span>
          <img v-else :src="file.url" alt="" class="el-upload-list__item-thumbnail" style="height: 100px;"/>
          <div :class="['file-name',{'file-doc-name' : !isImg(file)}]" @click.stop="">{{ file.name }}</div>
          <span v-if="!disabled" class="el-upload-list__item-actions">
                        <span class="el-upload-list__item-delete" @click.stop="handleRemove(file,imageList)">
                            <i class="el-icon-delete-solid" style="font-size: 24px;color: #cccccc;"></i>
                        </span>
                    </span>
        </div>
      </template>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img :src="dialogImageUrl" alt="" width="100%">
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      loading: {},
      dialogImageUrl: '',
      dialogVisible: false,
      resourcesUrl: process.env.VUE_APP_RESOURCES_URL
    }
  },
  props: {
    value: {
      default: '',
      type: String
    },
    affixList: {
      default: [],
      type: Array
    },
    disabled: {
      default: false,
      type: Boolean
    }
  },
  computed: {
    imageList () {
      let res = []
      // if (this.value) {
      // 	let imageArray = this.value.split(',')
      // 	for (let i = 0; i < imageArray.length; i++) {
      // 		res.push({url: this.resourcesUrl + imageArray[i], response: imageArray[i]})
      // 	}
      // }
      this.affixList.forEach((file) => {
        res.push({
          url: this.resourcesUrl + file.affixPath,
          response: file.affixPath,
          name: file.affixName
        })
      })
      // this.$emit('input', this.value)
      return res
    }
  },
  methods: {
    imageSave (file) {
      console.log('🚀 ~ file', file)
      // window.open(file.url)
      if (this.isImg(file) || this.isPdf(file)) {
        window.open(file.url)
      } else {
        this.downFile(file.url, file.name)
      }
    },
    downFile (url, fileName) {
      const x = new XMLHttpRequest()
      x.open('GET', url, true)
      x.responseType = 'blob'
      x.onload = function () {
        const url = window.URL.createObjectURL(x.response)
        const a = document.createElement('a')
        a.href = url
        a.download = fileName
        a.click()
      }
      x.send()
    },
    isImg (file) {
      if (file.raw) {
        //选择后的对象
        if (file.raw.type.indexOf('image') === -1) {
          return false
        } else {
          return true
        }

      } else {
        //上传后返回的对象
        const nameIndex = file.url.lastIndexOf('/')
        const name = file.url.substr(nameIndex + 1)
        const suffix = name.split('.')[1]?.toLocaleLowerCase()
        const imglist = ['svgz', 'pjp', 'png', 'ico', 'avif', 'tiff', 'tif', 'jfif', 'svg', 'xbm', 'pjpeg', 'webp', 'jpg', 'jpeg', 'bmp', 'gif']
        //const imglist = ['jpg','jpeg','png','bmp','webp','svg','txt','pdf','doc','docx','ppt','pptx','pps','ppsx','odt','xls','xlsx','wps','rar','zip','7z']
        console.info(suffix);
        const result = imglist.find(item => item === suffix)
        if (result) {
          return true
        } else {
          return false
        }
      }
    },
    isPdf (file) {
      const nameIndex = file.url.lastIndexOf('/')
      const name = file.url.substr(nameIndex + 1)
      const suffix = name.split('.')[1]?.toLocaleLowerCase()
      const imglist = ['pdf']

      const result = imglist.find(item => item === suffix)
      if (result) {
        return true
      } else {
        return false
      }
    },
    isTXT (file) {
      const nameIndex = file.url.lastIndexOf('/')
      const name = file.url.substr(nameIndex + 1)
      const suffix = name.split('.')[1]?.toLocaleLowerCase()
      const imglist = ['txt']

      const result = imglist.find(item => item === suffix)
      if (result) {
        return true
      } else {
        return false
      }
    },
    isZip (file) {
      const nameIndex = file.url.lastIndexOf('/')
      const name = file.url.substr(nameIndex + 1)
      const suffix = name.split('.')[1]?.toLocaleLowerCase()
      const imglist = ['rar','zip','7z']

      const result = imglist.find(item => item === suffix)
      if (result) {
        return true
      } else {
        return false
      }
    },
    isWord (file) {
      const nameIndex = file.url.lastIndexOf('/')
      const name = file.url.substr(nameIndex + 1)
      const suffix = name.split('.')[1]?.toLocaleLowerCase()
      const imglist = ['doc','docx','dot']

      const result = imglist.find(item => item === suffix)
      if (result) {
        return true
      } else {
        return false
      }
    },
    isExcel (file) {
      const nameIndex = file.url.lastIndexOf('/')
      const name = file.url.substr(nameIndex + 1)
      const suffix = name.split('.')[1]?.toLocaleLowerCase()
      const imglist = ['xls','xlsx']

      const result = imglist.find(item => item === suffix)
      if (result) {
        return true
      } else {
        return false
      }
    },
    // 上传时
    handleProgress(){
      this.loading = this.$loading({
        lock: true,
        text: '附件上传中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
    },
    // 图片上传成功
    handleUploadSuccess (response, file, fileList) {
      console.log('🚀 ~ response, file, fileList', response, file, fileList)
      // let pics = fileList.map(file => {
      // 	return file.response
      // }).join(',')
      this.loading.close();
      this.$emit('input', fileList)
    },
    handleError(){
      this.loading.close();
    },
    // 限制图片上传大小
    beforeAvatarUpload (file) {
      ///const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif' || file.type === 'image/jpg'
      //if (!isJPG) {
      //  this.$message.error('上传图片只能是jpeg/jpg/png/gif 格式!')
      //}
      const fileSuffix = file.name.substring(file.name.lastIndexOf(".") + 1);
      const whiteList = ["jpg","jpeg","png","txt","pdf","doc","docx","ppt","pptx","pps","ppsx","odt","xls","xlsx","wps"];

      if (whiteList.indexOf(fileSuffix) === -1) {
        this.$message.warning("上传文件格式不正确，请重新选择,可以传输文件类型.jpg,.jpeg,.png,.bmp,.webp,.svg,.txt, .pdf,.doc,.docx,.ppt,.pptx,.pps,.ppsx,.odt,.xls,.xlsx,.wps,.rar,.zip,.7z")
        return false;

      }
      const isJPG = true
      const isLt5M = file.size / 1024 / 1024 < 5
      if (!isLt5M) {
        this.$message.error('上传文件大小不能超过 5MB!')
      }
      return isLt5M && isJPG
    },
    handleRemove (file, fileList) {
      console.log('🚀 ~ file', file)
      console.log('🚀 ~ fileList', fileList)
      // let pics = fileList.map(file => {
      // 	return file.response
      // }).join(',')
      for (let i = fileList.length - 1; i >= 0; i--) {
        if (fileList[i].response === file.response) {
          fileList.splice(i, 1)
        }
      }
      this.$emit('input', fileList)
    },
    handlePictureCardPreview (file) {
      // console.log('🚀 ~ file', file)
      let fileArr = file.url.split('.')
      let imgType = ['png', 'jpg', 'JPG', 'PNG']
      if (fileArr.length) {
        if (imgType.includes(fileArr[fileArr.length - 1])) {
          this.dialogImageUrl = file.url
          this.dialogVisible = true
        } else {
          location.href = file.url
        }
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.upload-content {
  min-height: 150px;
  display: flex;
  align-items: flex-start;
  .el-upload__tip {
    display: block;
    height: 30px;
    line-height: 30px;
  }

  .el-upload-list_file {
    position: absolute;
    width: 100%;
    height: 100%;
    left: 0;
    top: 0;
    cursor: default;
    display: inline-flex;
    justify-content: center;
    align-items: center;
    font-size: 20px;
    transition: opacity var(--el-transition-duration);
  }

  .file-name {
    position: absolute;
    top: 105px;
    left: 0;
    width: 100px;
    display: flex;
    height: 50px;
    line-height: 25px;
    justify-content: center;
    align-items: flex-start;
    overflow: hidden;
  }

  .file-doc-name {
    position: absolute;
    top: 105px;
    left: 0;
    display: flex;
    width: 100px;
    height: 50px;
    line-height: 25px;
    justify-content: center;
    align-items: flex-start;
    overflow: hidden;
  }
}

.file-box {
  :deep() {
    .el-upload--picture-card {
      width: 108px;
      height: 108px;
      margin: 3px 8px 8px 8px;
      border: 2px dashed #c0ccda;
    }

    .el-upload-list--picture {
      margin-bottom: 20px;
    }

    .el-upload-list__item {
      width: 108px;
      height: 108px;
      margin: 3px 8px 60px 8px;
      overflow: auto;
    }
  }

  .file-name {
    text-align: center;
    width: 108px;
    height: auto;
    display: flex;
    max-height: 60px;
    justify-content: center;
    overflow-y: scroll;
  }

  .file-doc-name {
    position: absolute;
    top: 110px;
  }
}

.limitshow {
  :deep() {
    .el-upload--picture-card {
      display: none;
    }
  }
}

</style>

